﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cloud.Boss.Models;
using Cloud.Dto;
using Cloud.Dto.Sys;
using Cloud.Framework.Filter;
using Cloud.Service.Log;
using Cloud.Service.Module;
using Cloud.Service.Role;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace Cloud.Boss.Controllers
{
    public class SysModuleController : BaseController
    {
        private readonly IModuleService _moduleService;
        public SysModuleController(
            IOptions<ProjectSetting> _projectSetting,
            ILogService _logService,
            IModuleService _moduleService
            ) : base(_projectSetting, _logService)
        {
            this._moduleService = _moduleService;
        }
        public IActionResult Manager()
        {
            return View();
        }
        public async Task<IActionResult> GetMenuTree(int id = -1)
        {
            if (id == -1)
            {
                var list = new
                {
                    id = 0,
                    name = "菜单树",
                    isParent = true,
                    @checked = false
                };
                return Json(list);

            }
            else
            {
                var moduleList = await _moduleService.GetModuleByParentId(id);
                var list = moduleList.Select(c => new
                {
                    id = c.ModuleId,
                    name = c.ModuleName,
                    isParent = c.IsParent
                }).ToList();
                return Json(list);
            }

        }

        [HttpGet]
        public IActionResult Edit(int id = 0, int parentId = 0)
        {
            var model = _moduleService.Init(id, parentId).Info;
            return View(model);

        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(ModuleDto model)
        {
            if (string.IsNullOrEmpty(model.ModuleName))
            {
                return ErrorJsonResult("菜单名称不能为空");
            }
            try
            {
                _moduleService.Info = model;

                return SuccessJsonResult(model.ModuleId == 0 ? "add:" + _moduleService.ModuleId : "edit:" + _moduleService.ModuleId);
            }
            catch (Exception ex)
            {

                return ErrorJsonResult(ex.Message);
            }

        }
        [HttpGet]
        public async Task<IActionResult> Delete(int id = 0)
        {
            try
            {
                await _moduleService.Init(id,0).Delete();
                return SuccessJsonResult();
            }
            catch (Exception ex)
            {

                return ErrorJsonResult(ex.Message);
            }


        }
    }
}